﻿/* ***********************************************
 * author : 
 * email  : 
 * history: 
 * ***********************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Dynamic;
using System.Linq.Expressions;
using DBA.Common;
using DBA.Data.ADO;
using DBA.Data.Hibernate;

namespace DBA.Data
{
    /// <summary>
    /// 处理数据的添加、修改
    /// </summary>
    public class ManagerSQL
    {
        /// <summary>
        /// 数据访问函数库的实例，主要是想操作Connection
        /// </summary>
        public  DataAccessLibrary dal;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="dal">数据访问函数库的实例</param>
        public ManagerSQL(DataAccessLibrary dal)
        {
            this.dal = dal;
        }

        public enum PageViewTableType
        {

            // 单表
            SimpleTable = 1,
            //复合表可能引发主键重合
            MixtureTable = 2
        }

        #region 得到数据库对象
        /// <summary>
        /// 给对象的ID赋值后传入得到一个实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetEntity<T>(T obj)
        {
            dal.ManagerParameter.ClearParameter();
            string SqlStr = "select * from {tablename} where {pkstr}";
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            SqlStr = SqlStr.Replace("{pkstr}", ormProperty.PrimaryKey + "=@" + ormProperty.PrimaryKey);
            OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(ormProperty.PrimaryKey);
            dal.ManagerParameter.AddNewInParameter(ormProperty.PrimaryKey,
                PropertyHelper.GetValue(obj, ormProperty.PrimaryKey),
                ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                tmpOrmAttribute.ParameterLength);
            return dal.ExecuteFillObject<T>(SqlStr);
        }

        public dynamic GetEntity(Object obj)
        {
            dynamic dynList = new ExpandoObject();
            return dynList;
        }

        /// <summary>
        /// 根据传递来的主键值得到一个实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public T GetEntity<T>(Object obj)
        {
            dal.ManagerParameter.ClearParameter();
            string SqlStr = "select * from {tablename} where {pkstr}";
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            SqlStr = SqlStr.Replace("{pkstr}", ormProperty.PrimaryKey + "=@" + ormProperty.PrimaryKey);
            OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(ormProperty.PrimaryKey);
            dal.ManagerParameter.AddNewInParameter(ormProperty.PrimaryKey,
                obj,
                ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                tmpOrmAttribute.ParameterLength);
            return dal.ExecuteFillObject<T>(SqlStr);
        }

        public T GetEntityField<T>(Object obj, string filedName)
        {
            dal.ManagerParameter.ClearParameter();
            string SqlStr = "select {filedName} from {tablename} where {pkstr}";
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            SqlStr = SqlStr.Replace("{filedName}", "[" + filedName + "]");
            SqlStr = SqlStr.Replace("{pkstr}", ormProperty.PrimaryKey + "=@" + ormProperty.PrimaryKey);
            OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(ormProperty.PrimaryKey);
            dal.ManagerParameter.AddNewInParameter(ormProperty.PrimaryKey,
                obj,
                ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                tmpOrmAttribute.ParameterLength);
            return dal.ExecuteScalar<T>(SqlStr,filedName);
        }

        /// <summary>
        /// 根据SQL得到DATATABLE
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable Select(string sql)
        {
            dal.ManagerParameter.ClearParameter();
            return dal.ExecuteFillDataTable(sql);
        }

        /// <summary>
        /// 执行多条语句或者存储过程得到多个结果表集
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="paras"></param>
        /// <param name="isPro"></param>
        /// <returns></returns>
        public DataSet Select(string sql,Dictionary<string, object> paras, bool isPro)
        {
            dal.ManagerParameter.ClearParameter();
            foreach (KeyValuePair<string, object> pair in paras)
            {
                dal.ManagerParameter.AddNewInParameter(pair.Key, pair.Value);
            }
            return dal.ExecuteFillDataSet(sql, isPro);
        }

        /// <summary>
        /// 根据传入SQL和条件得到执行的DATATABLE
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="adoCondition"></param>
        /// <returns></returns>
        public DataTable Select(string sql, IList<AdoCondition> adoCondition)
        {
            dal.ManagerParameter.ClearParameter();
            string where = string.Empty;
            string order = string.Empty;
            SqlParasContains sqlAndParas = new SqlBuilder(adoCondition).GetSqlAndParas();
            if (adoCondition.Count > 0)
            {
                where = "where " + sqlAndParas.whereStr.TrimStart("and".ToCharArray()).TrimStart("or".ToCharArray());
                if (!VerificationHelper.IsNullOrEmpty<string>(sqlAndParas.OrderStr))
                {
                    order = " order by " + sqlAndParas.OrderStr;
                }
            }

            foreach (KeyValuePair<string, object> pair in sqlAndParas.paras)
            {
                dal.ManagerParameter.AddNewInParameter(pair.Key, pair.Value);
            }
            string sqlStr = (sql+" {0} {1}").FormatWith(where, order);
            return dal.ExecuteFillDataTable(sql);
        }

        public IList<T> Select<T>(string sql) where T : new()
        {
            dal.ManagerParameter.ClearParameter();
            return dal.ExecuteFillObjects<T>(sql);
        }
        /// <summary>
        /// 得到单表的所有数据，以实体的方式
        /// </summary>
        /// <typeparam name="T">实体对象类型</typeparam>
        /// <returns></returns>
        public IList<T> Select<T>() where T : new()
        {
            dal.ManagerParameter.ClearParameter();
            string SqlStr = "select * from {tablename} ";
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            return dal.ExecuteFillObjects<T>(SqlStr);
        }

        /// <summary>
        /// 得到单表的数据，根据相关条件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public IList<T> Select<T>(Expression<Func<T, bool>> func) where T : new()
        {
            dal.ManagerParameter.ClearParameter();
            string where = string.Empty;
            if (func.Body is BinaryExpression)
            {
                BinaryExpression be = ((BinaryExpression)func.Body);
                where = "where " +  ExpressionHelper.BinarExpressionProvider(be.Left, be.Right, be.NodeType);
            }
            string sql = "select * from [{1}] {2}".FormatWith(AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>().TableName, where);

            return dal.ExecuteFillObjects<T>(sql);
        }

        /// <summary>
        /// 根据查询条件得到集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="adoCondition"></param>
        /// <returns></returns>
        public IList<T> Select<T>(IList<AdoCondition> adoCondition) where T : new()
        {
            dal.ManagerParameter.ClearParameter();
            string where = string.Empty;
            string order = string.Empty;
            SqlParasContains sqlAndParas = new SqlBuilder(adoCondition).GetSqlAndParas();
            if (adoCondition.Count > 0)
            {
                where = "where " + sqlAndParas.whereStr.TrimStart("and".ToCharArray()).TrimStart("or".ToCharArray());
                if (!VerificationHelper.IsNullOrEmpty<string>(sqlAndParas.OrderStr))
                {
                    order = " order by " + sqlAndParas.OrderStr;
                }
            }
            
            foreach (KeyValuePair<string, object> pair in sqlAndParas.paras)
            {
                dal.ManagerParameter.AddNewInParameter(pair.Key, pair.Value);
            }
            string sql = "select * from [{1}] {2} {3}".FormatWith(AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>().TableName, where, order);
            return dal.ExecuteFillObjects<T>(sql);
        }


        /// <summary>
        /// 根据查询条件得到集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="adoCondition"></param>
        /// <returns></returns>
        public virtual IList<T> Select<T>(IList<AdoCondition> adoCondition, int pageCurrent, int pageSize, ref int recordCount) where T : new()
        {
            return null;
        }

        /// <summary>
        /// 根据查询条件得到集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="adoCondition"></param>
        /// <returns></returns>
        public int GetMaxCount<T>(IList<AdoCondition> adoCondition) where T : new()
        {
            dal.ManagerParameter.ClearParameter();
            string where = string.Empty;
            string order = string.Empty;
            SqlParasContains sqlAndParas = new SqlBuilder(adoCondition).GetSqlAndParas();
            if (adoCondition.Count > 0)
            {
                where = "where " + sqlAndParas.whereStr.TrimStart(' ').TrimStart("and".ToCharArray()).TrimStart("or".ToCharArray());
                if (!VerificationHelper.IsNullOrEmpty<string>(sqlAndParas.OrderStr))
                {
                    order = " order by " + sqlAndParas.OrderStr;
                }
            }

            foreach (KeyValuePair<string, object> pair in sqlAndParas.paras)
            {
                dal.ManagerParameter.AddNewInParameter(pair.Key, pair.Value);
            }
            string sql = "select count(*) from [{0}] {1} {2}".FormatWith(AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>().TableName, where, order);
            return ConvertHelper.ToInt32(dal.ExecuteScalar(sql));
        }

        #endregion

        #region 插入对象
        /// <summary>
        /// 添加记录。传入表名，字段数组，值数组，返回新生成记录的ID(仅限于MS SQL数据库，且表里有自增字段)
        /// </summary>
        /// <param name="tableName">要添加记录的表的名称</param>
        /// <param name="columnName">字段名数组</param>
        /// <param name="columnValue">字段对应的值的数组</param>
        /// <returns></returns>
        public virtual string Insert(string tableName, string[] columnName, string[] columnValue)
        {
            //添加数据，Oledb\Odbc都在这里实现，其他的（SqlClient等）在子类里面实现，
            System.Text.StringBuilder SQL = new System.Text.StringBuilder(800);
            SQL.Append("insert into ");					//insert into 
            SQL.Append(tableName);
            SQL.Append(" (");
            int i;

            #region 字段
            for (i = 0; i < columnName.Length; i++)		//字段
            {
                if (columnValue[i] != null)
                {
                    SQL.Append(columnName[i]);
                    SQL.Append(",");
                }
            }
            SQL = SQL.Remove(SQL.Length - 1, 1);
            #endregion

            SQL.Append(")  values ('");

            #region 值
            for (i = 0; i < columnName.Length; i++)     //字段对应的值
            {
                if (columnValue[i] != null)
                {
                    SQL.Append(columnValue[i]);
                    SQL.Append("','");
                }
            }
            SQL = SQL.Remove(SQL.Length - 2, 2);
            #endregion

            SQL.Append(") ");

            string re = dal.ExecuteString(SQL.ToString(), "InsertData_SQL");
            SQL.Length = 0;
            return re;

        }


        /// <summary>
        /// 插入一个实体对象
        /// </summary>
        /// <typeparam name="T">数据库映射对象</typeparam>
        /// <param name="t">数据库映射对象实体</param>
        /// <returns></returns>
        public virtual int Insert<T>(T t)
        {
            dal.ManagerParameter.ClearParameter();
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string SqlStr = "insert into {tablename} ({namestr}) values({varstr})";
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            PropertyInfo[] pro = typeof(T).GetProperties();
            string varstr = String.Empty;
            string namestr = String.Empty;
            foreach (PropertyInfo propertyInfo in pro)
            {
                if (ormProperty.PrimaryKey.ToLower() == propertyInfo.Name.ToLower() && ormProperty.PrimaryKeyType == "IDENTITY")
                    continue;
                namestr += ",[" + propertyInfo.Name + "]";
                varstr += ",@" + propertyInfo.Name;
                OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(propertyInfo.Name);
                dal.ManagerParameter.AddNewInParameter(propertyInfo.Name,
                    ChargeValue(propertyInfo, t),
                    ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                    tmpOrmAttribute.ParameterLength);
            }
            varstr = varstr.TrimStart(',');
            namestr = namestr.TrimStart(',');
            SqlStr = SqlStr.Replace("{namestr}", namestr);
            SqlStr = SqlStr.Replace("{varstr}", varstr);
            string re = dal.ExecuteString(SqlStr, "InsertData_Parameters");

            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("InsertData_Parameters", tableName, "添加数据时出现异常！");
                return 0;
            }
            return 1;
        }

        public virtual int InsertGetID<T>(T t)
        {
            dal.ManagerParameter.ClearParameter();
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string SqlStr = "insert into {tablename} ({namestr}) values({varstr})";
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            PropertyInfo[] pro = typeof(T).GetProperties();
            string varstr = String.Empty;
            string namestr = String.Empty;
            foreach (PropertyInfo propertyInfo in pro)
            {
                if (ormProperty.PrimaryKey.ToLower() == propertyInfo.Name.ToLower() && ormProperty.PrimaryKeyType == "IDENTITY")
                    continue;
                namestr += ",[" + propertyInfo.Name + "]";
                varstr += ",@" + propertyInfo.Name;
                OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(propertyInfo.Name);
                dal.ManagerParameter.AddNewInParameter(propertyInfo.Name,
                    ChargeValue(propertyInfo, t),
                    ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                    tmpOrmAttribute.ParameterLength);
            }
            varstr = varstr.TrimStart(',');
            namestr = namestr.TrimStart(',');
            SqlStr = SqlStr.Replace("{namestr}", namestr);
            SqlStr = SqlStr.Replace("{varstr}", varstr);
            SqlStr += "SELECT  @@IDENTITY   AS   'Identity '";
            string re = dal.ExecuteString(SqlStr, "InsertData_Parameters");

            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("InsertData_Parameters", tableName, "添加数据时出现异常！");
                return -1;
            }
            return int.Parse(re);
        }

        /// <summary>
        /// 根据存储过程的参数的信息，自动拼接参数化的SQL语句，用于添加数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public virtual string Insert(string tableName)
        {
            if (dal.Command.Parameters.Count == 0)
            {
                dal.SetErrorMessage("InsertData_Parameters", tableName, "没有参数，无法自动拼接参数化的SQL语句");
                return "没有参数，无法自动拼接参数化的SQL语句";
            }

            //添加数据	返回新添加的ID，在子类里实现
            System.Text.StringBuilder SQL = new System.Text.StringBuilder(1000);
            SQL.Append("insert into ");					//insert into 
            SQL.Append(tableName);
            //SQL.Append(" ([");
            SQL.Append(" (");
            int i;

            #region 字段
            string tmp = "";
            for (i = 0; i < dal.Command.Parameters.Count; i++)		//字段
            {
                if (dal.Command.Parameters[i].Value != null)
                {
                    tmp = dal.Command.Parameters[i].ParameterName;
                    tmp = tmp.Substring(1);
                    SQL.Append(tmp);
                    //SQL.Append("],[");
                    SQL.Append(",");
                }
            }
            SQL = SQL.Remove(SQL.Length - 1, 1);
            #endregion

            SQL.Append(")  values (");

            #region 值
            for (i = 0; i < dal.Command.Parameters.Count; i++)     //字段对应的值
            {
                if (dal.Command.Parameters[i].Value != null)
                {
                    SQL.Append(dal.Command.Parameters[i].ParameterName);
                    SQL.Append(",");
                }
            }
            SQL = SQL.Remove(SQL.Length - 1, 1);
            #endregion

            //获取新添加的记录的主键值，自增字段有效
            SQL.Append(") ");

            string re = dal.ExecuteString(SQL.ToString(), "InsertData_Parameters");
            SQL.Length = 0;

            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("InsertData_Parameters", tableName, "添加数据时出现异常！");
                return "添加数据时出现异常！";
            }

            return re;

        }
        #endregion

        #region 修改数据
        /// <summary>
        /// 修改记录。传入表名，字段数组，值数组 ，修改条件
        /// </summary>
        /// <param name="tableName">要修改记录的表的名称</param>
        /// <param name="columnName">字段名数组</param>
        /// <param name="columnValue">字段对应的值的数组</param>
        /// <param name="query">条件 ，加在where 后面的语句</param>
        /// <returns></returns>
        public virtual bool Update(string tableName, string[] columnName, string[] columnValue, string query)
        {
            //修改记录的方式是一样的，就在基类里面实现了。
            System.Text.StringBuilder SQL = new System.Text.StringBuilder(500);
            SQL.Append("update ");					//update
            SQL.Append(tableName);
            SQL.Append(" set ");
            int i;

            #region 字段 = 值
            for (i = 0; i < columnName.Length; i++)
            {
                if (columnValue[i] != null)
                {
                    SQL.Append("[");
                    SQL.Append(columnName[i]);					//update
                    SQL.Append("]='");
                    SQL.Append(columnValue[i]);
                    SQL.Append("',");
                }
                //else
                //{
                //    SQL.Append("]='',");
                //}

            }
            SQL = SQL.Remove(SQL.Length - 1, 1);	//去掉最后一个 ","
            #endregion

            SQL.Append(" where ");
            SQL.Append(query);

            dal.ExecuteNonQuery(SQL.ToString(), "UpdateData_SQL" );
            SQL.Length = 0;
            return true;

        }

        /// <summary>
        /// 更新对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual string Update<T>(T t)
        {
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string SqlStr = "update {tablename} set {varstr} where {pkstr}";
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            SqlStr = SqlStr.Replace("{pkstr}", ormProperty.PrimaryKey + "=@" + ormProperty.PrimaryKey);
            PropertyInfo[] pro = typeof(T).GetProperties();
            string varstr = String.Empty;
            dal.ManagerParameter.ClearParameter();
            foreach (PropertyInfo propertyInfo in pro)
            {
                OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(propertyInfo.Name);
                dal.ManagerParameter.AddNewInParameter(propertyInfo.Name,
                    ChargeValue(propertyInfo, t),
                    ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                    tmpOrmAttribute.ParameterLength);
                if (propertyInfo.Name == ormProperty.PrimaryKey) continue;
                varstr += "," + propertyInfo.Name + "=@" + propertyInfo.Name;
            }
            varstr = varstr.TrimStart(',');
            SqlStr = SqlStr.Replace("{varstr}", varstr);
            string re = dal.ExecuteString(SqlStr, "update_Parameters");

            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("InsertData_Parameters", tableName, "添加数据时出现异常！");
                return "0";
            }
            return re;
        }

        /// <summary>
        /// 修改记录。传入表名 ，修改条件
        /// </summary>
        /// <param name="tableName">要修改记录的表的名称</param>
        /// <param name="query">条件 ，加在where 后面的语句</param>
        /// <returns></returns>
        public virtual string Update(string tableName, string query)
        {
            //修改记录的方式是一样的，就在基类里面实现了。
            System.Text.StringBuilder SQL = new System.Text.StringBuilder(500);
            SQL.Append("update ");					//update
            SQL.Append(tableName);
            SQL.Append(" set ");
            int i;

            #region 字段 = 值
            string tmp = "";
            for (i = 0; i < dal.Command.Parameters.Count; i++)
            {
                tmp = dal.Command.Parameters[i].ParameterName;
                tmp = tmp.Substring(1);

                SQL.Append("");
                SQL.Append(tmp);					//update

                SQL.Append("=");
                SQL.Append(dal.Command.Parameters[i].ParameterName);
                SQL.Append(",");

            }
            SQL = SQL.Remove(SQL.Length - 1, 1);	//去掉最后一个 ","
            #endregion

            SQL.Append(" where ");
            SQL.Append(query);

            dal.ExecuteNonQuery(SQL.ToString(), "UpdateData_Parameters");
            SQL.Length = 0;

            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("UpdateData_Parameters", tableName, "修改数据时出现异常！");
                return "修改数据时出现异常！";
            }

            return "";

        }
        #endregion

        #region 删除数据
        /// <summary>
        /// 删除一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int Delete<T>(T obj)
        {
            OrmPropertyAttribute ormProperty = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>();
            string SqlStr = "Delete from {tablename} where {pkstr}";
            string tableName = ormProperty.TableName;
            SqlStr = SqlStr.Replace("{tablename}", "[" + tableName + "]");
            SqlStr = SqlStr.Replace("{pkstr}", ormProperty.PrimaryKey + "=@" + ormProperty.PrimaryKey);
            OrmPropertyAttribute tmpOrmAttribute = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>(ormProperty.PrimaryKey);
            dal.ManagerParameter.AddNewInParameter(ormProperty.PrimaryKey,
                PropertyHelper.FindProName<T>(ormProperty.PrimaryKey, obj).FastGetValue<T>(obj),
                ConvertHelper.ConvertStringToSqlserverDbType(tmpOrmAttribute.ParameterType),
                tmpOrmAttribute.ParameterLength);
            dal.ExecuteNonQuery(SqlStr, "Delete_Parameters");

            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("Delete_Parameters", tableName, "修改数据时出现异常！");
                return 0;
            }
            return 1;
        }

        /// <summary>
        /// 根据解析式解析条件生成sql
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public int Delete<T>(Expression<Func<T, bool>> func)
        {
            string where = string.Empty;
            string tableName = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>().TableName;
            if (func.Body is BinaryExpression)
            {
                BinaryExpression be = ((BinaryExpression)func.Body);
                where = "where " + ExpressionHelper.BinarExpressionProvider(be.Left, be.Right, be.NodeType);
            }
            string sql = "delete from [{0}] {1}".FormatWith(tableName, where);
            dal.ExecuteNonQuery(sql, "Delete_Parameters");
            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("Delete_Parameters", tableName, "修改数据时出现异常！");
                return 0;
            }
            return 1;
        }

        /// <summary>
        /// 根据条件来删除对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public int Delete<T>(IList<AdoCondition> adoCondition) where T : new()
        {
            string where = string.Empty;
            string tableName = AttributeHelper.GetAAttribute<OrmPropertyAttribute, T>().TableName;
            dal.ManagerParameter.ClearParameter();
            SqlParasContains sqlAndParas = new SqlBuilder(adoCondition).GetSqlAndParas();
            if (adoCondition.Count > 0)
            {
                where = "where " + sqlAndParas.whereStr.TrimStart(" and".ToCharArray()).TrimStart(" or".ToCharArray());
            }
            foreach (KeyValuePair<string, object> pair in sqlAndParas.paras)
            {
                dal.ManagerParameter.AddNewInParameter(pair.Key, pair.Value);
            }
            string sql = "delete from [{0}] {1}".FormatWith(tableName, where);
            dal.ExecuteNonQuery(sql, "Delete_Parameters");
            if (dal.ErrorMessage.Length > 2)
            {
                //出错了，需要把参数值也记录到错误日志里面，以便于修改错误。
                dal.SetErrorMessage("Delete_Parameters", tableName, "修改数据时出现异常！");
                return 0;
            }
            return 1;
        }
        #endregion



        #region 根据存储过程的参数的信息，自动拼接参数化的SQL语句，用于添加数据



        public object ChargeValue<T>(PropertyInfo pro, T obj)
        {
            object val = pro.FastGetValue<T>(obj);
            if (pro.PropertyType == typeof(int))
            {
                if (val.ToString() == "-1")
                    val = DBNull.Value;
            }
            else if (pro.PropertyType == typeof(string))
            {
                if (val == null)
                    val = DBNull.Value;
            }
            else if (pro.PropertyType == typeof(decimal))
            {
                if (val.ToString() == "-1")
                    val = DBNull.Value;
            }
            else if (pro.PropertyType == typeof(DateTime))
            {
                if (val.ToString() == DateTime.MinValue.ToString())
                    val = DBNull.Value;
            }
            else if (pro.PropertyType == typeof(bool))
            {
                if (val == null)
                    val = DBNull.Value;
            }
            return val;
        }

        #endregion








        #region 提供分页查询基类方法，子类必须重写了此方法才能返回数据，目前只有sqlserver实现了此方法
        /// <summary>
        /// Author:samfeng
        /// </summary>
        /// <param name="tablename">表名，可以是多表</param>
        /// <param name="fieldShow">字段显示</param>
        /// <param name="where">条件</param>
        /// <param name="sort">索引排序</param>
        /// <param name="pageCurrent">当前页</param>
        /// <param name="pageSize">页尺寸</param>      
        /// <param name="tableType">表类型</param>
        /// <param name="recordCount">记录总数</param>       
        /// <returns>返回DataTable类型</returns>
        public virtual DataTable GetPageDataTable(string tablename, string fieldShow, string where, string sort, int pageCurrent, int pageSize, PageViewTableType tableType, ref int recordCount)
        {
            return null;
        }
        #endregion


    }
}
